<template>
  <div id="fill">
    <div class="prompt">
      <span>提示：因食材数量有限，订单预定后不可更改</span>
    </div>
    <div class="Fill-wrapper">
      <div class="fill-content">
        <span>用户名</span>
        <input v-model="username" placeholder="请填写您的用户名">
      </div>
      <div class="fill-content">
        <span>房间号</span>
        <input v-model="value1" readonly placeholder="请填写您的房间号">
      </div>
      <div class="fill-content">
        <span>手机号</span>
        <input v-model="value2" oninput="if(value.length>11) value=value.slice(0,11)" placeholder="请填写您的手机号" type="number">
      </div>
      <div class="fill-content">
        <span>用餐人数</span>
        <input v-model="value3" placeholder="请填写您的用餐人数" type="number">
      </div>
      <div class="fill-content">
        <span>备注</span>
        <input placeholder="请填写口味偏好或其他备注" v-model="remark">
      </div>
    </div>
    <div class="content-wrapper" >
          <group>
            <popup-picker :title="title"  :data="list2" v-model="valueTime" placeholder="请选择用餐时间"></popup-picker>
          </group>
        <div class="content-nav" v-for="item of foods" :key="item.index">
          <div class="content-title">
            <span><img :src="item.imgurl"></span>
            <span class="content-number">
              <span>{{item.name}}</span>
              <span class="deal">x{{item.count}}</span>
            </span>
          </div>
          <div class="content-price">￥{{item.price}}</div>
        </div>
      </div>
      <div class="pay-nav">
        <div class="null"></div>
        <div class="link-fill" id="pay" @click="linkFill">
          <div class="go-pay">预定：￥{{price}}</div>
        </div>
      </div>
  </div>
</template>

<script>
import apis from '../../../static/js/apis'
import { Datetime, PopupPicker, Group, Cell, Picker, XButton, Divider, XSwitch } from 'vux'
export default {
  components: {
    PopupPicker,
    Group,
    Picker,
    XButton,
    Divider,
    Cell,
    XSwitch,
    Datetime,
    apis
  },
  data () {
    return {
      dateTime: '',
      currentTime: '',
      endTime: '',
      title: '时间',
      msg: '',
      value1: '',
      value2: '',
      value3: '',
      time: [],
      remark: '',
      list2: [
        ['11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '17:00', '17:30', '18:00',
          '18:30', '19:00', '19:30', '20:00']
      ],
      choose: '选择您的用餐时间',
      valueTime: [],
      clicktime: '',
      foods: [],
      price: '',
      userid: '',
      username: '',
      receiptid: ''
    }
  },
  created () {
    var dateTime = new Date()
    var s2 = dateTime.getFullYear() + '-' + (dateTime.getMonth() + 1) + '-' + dateTime.getDate()
    this.currentTime = s2
    this.endTime = dateTime.setTime(dateTime.getTime() + 24 * 60 * 60 * 1000)
    var s3 = dateTime.getFullYear() + '-' + (dateTime.getMonth() + 1) + '-' + dateTime.getDate()
    this.endTime = s3
    this.time.push(this.currentTime)
    this.time.push(this.endTime)
    this.list2.unshift(this.time)
    this.foods = JSON.parse(this.$route.query.selectFoods)
    this.price = this.$route.query.totalPrice
    this.userid = localStorage.getItem('userId')
    this.usermsg()
  },
  methods: {
    // 生成5位随机数
    RndNum (n) {
      let rnd = ''
      for (let i = 0; i < n; i++) {
        rnd += Math.floor(Math.random() * 10)
      }
      return rnd
    },
    // 返回当前日期字符串
    getNowFormatDate () {
      let date = new Date()
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      let currentdate = date.getFullYear().toString() + month.toString() + strDate.toString()
      return currentdate
    },
    usermsg () {
      this.$axios
        .post(
          apis + '/shenglian-fast/app/weixinapp/getroomuser',
          {
            userid: this.userid
          }
        )
        .then(response => {
          if (response.data.msg === 'success') {
            let data = response.data
            this.value1 = data.roominfo.roomcode
            this.username = data.userinfo.nickname
          }
        })
        .catch(error => {
          console.log(error)
          this.$dialog.toast({mes: '服务器异常，稍后再试！', timeout: 1000})
        })
    },
    linkFill () {
      document.getElementById('pay').style.pointerEvents = 'none'
      if (this.username === '') {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '请填写用户名', timeout: 1000})
      } else if (this.value1 === '') {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '房间号不能为空，请绑定后再操作', timeout: 1000})
      } else if (this.value2 === '') {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '请填写手机号', timeout: 1000})
      } else if (this.value3 === '') {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '请填写用餐人数', timeout: 1000})
      } else if (this.valueTime.length === 0) {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '请选择用餐时间', timeout: 1000})
      } else if (!(/^[1][3,4,5,7,8][0-9]{9}$/.test(this.value2))) {
        document.getElementById('pay').style.pointerEvents = ''
        this.$dialog.toast({mes: '手机号格式不正确', timeout: 1000})
      } else {
        this.clicktime = this.valueTime[0].toString() + ' ' + this.valueTime[1].toString()
        let rod = this.RndNum(5)
        let date = this.getNowFormatDate()
        let receiptcode = date + '' + rod
        if (this.price <= 0) {
          document.getElementById('pay').style.pointerEvents = ''
          this.$dialog.toast({mes: '商品总价不能小于0元', timeout: 1000})
        } else {
          this.$axios
            .post(
              apis + '/shenglian-fast/app/weixinapp/recepitsub',
              {
                username: this.username, // 用户名
                userid: this.userid, // 用户id
                roomcode: this.value1, // 房间号
                phone: this.value2, // 电话
                people: this.value3, // 人数
                remark: this.remark, // 备注
                sendtime: this.clicktime, // 就餐时间
                totalmoney: this.price, // 总金额
                recepitinfo: this.foods, // 菜品
                receiptcode: receiptcode // 订单号
              }
            )
            .then(response => {
              if (response.data.msg === 'success') {
                let receiptid = response.data.receiptid
                this.receiptid = receiptid
                this.$router.push({
                  path: '/success',
                  query: {
                    receiptid: this.receiptid
                  }
                })
                // let data = response.data.result
                // this.weixinPay(data) // 调支付
              } else {
                document.getElementById('pay').style.pointerEvents = ''
                this.$dialog.toast({mes: '数据提交错误，请联系管理员', timeout: 1000})
              }
            })
            .catch(error => {
              console.log(error)
              document.getElementById('pay').style.pointerEvents = ''
              this.$dialog.toast({mes: '服务器异常，稍后再试！', timeout: 1000})
            })
        }
      }
    },
    weixinPay (data) {
      var vm = this
      if (typeof WeixinJSBridge === 'undefined') { // 微信浏览器内置对象。参考微信官方文档
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
          document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
        }
      } else {
        vm.onBridgeReady(data)
      }
      document.getElementById('pay').style.pointerEvents = ''
    },
    onBridgeReady (data) {
      var vm = this
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          'appId': data.appId, // 公众号名称，由商户传入
          'timeStamp': data.timeStamp, // 时间戳，自1970年以来的秒数
          'nonceStr': data.nonceStr, // 随机串
          'package': data.package,
          'signType': data.signType, // 微信签名方式：
          'paySign': data.paySign // 微信签名
        },
        function (res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          console.log(res)
          // 获取支付信息
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // vm.$dialog.toast({mes: '支付成功', timeout: 2000})
            vm.$axios
              .post(
                apis + '/shenglian-fast/app/weixinapp/paysuccess',
                {
                  receiptid: vm.receiptid // 订单id
                }
              )
              .then(response => {
                if (response.data.msg === 'success') {
                  vm.$router.push({
                    path: '/success',
                    query: {
                      receiptid: vm.receiptid
                    }
                  })
                } else {
                  vm.$dialog.toast({mes: '订单信息状态提交错误，请联系管理员', timeout: 1000})
                }
              })
              .catch(error => {
                console.log(error)
                vm.$dialog.toast({mes: '服务器异常，稍后再试！', timeout: 1000})
              })
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            vm.$dialog.toast({mes: '取消支付', timeout: 2000})
            vm.$router.push({
              path: '/list'
            })
          } else {
            vm.$dialog.toast({mes: '支付失败', timeout: 2000})
            vm.$router.push({
              path: '/list'
            })
          }
        }
      )
    }
  }
}
</script>

<style scoped>
.prompt {
  padding: 0 23px;
  height: 44px;
  background-color: #f0f8fb;
  line-height: 44px;
  font-size: 10px;
}
.Fill-wrapper {
  margin: 8px;
  background-color: #FFFFFF;
}
.fill-content {
  display: flex;
  justify-content: space-between;
  margin: 0 12px;
  padding: 3px 0;
  border-top: 1px solid #F2F2F2;
}
.fill-content span {
  font-size: 12px;
  color: #333333;
  line-height: 38px;
}
.fill-content input {
  outline-style: none;
  border:none;
  height: 38px;
  color: #92d4ef;
  width: 150px;
  font-size: 12px;
  text-align: right;
}
.content-wrapper {
  box-sizing: border-box;
  margin: 0 8px ;
  padding: 0 8px;
  margin-top: 8px;
  background-color: #FFF;
  overflow: auto;
  height: 100%;
  margin-bottom: 49px;
}
.content-wrapper >>> .weui-cells {
  margin: 0;
}
.content-wrapper >>> .weui-cell {
  padding: 0;
}
.content-wrapper >>> .weui-label {
  font-size: 12px;
}
.content-wrapper >>> .vux-popup-picker-value{
  font-size: 12px;
  line-height: 44px;
  color: #92d4ef;
}
.content-wrapper >>> .vux-popup-picker-placeholder{
  font-size: 12px;
  line-height: 44px;
}
.content-date {
  height: 45px;
  line-height: 45px;
  /*margin-left: 235px;*/
  display: flex;
  justify-content: flex-end;
  font-size: 12px;
  color: #92D4EF;
  /*float: right;*/
}
.content-nav {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid  #F2F2F2;
  padding: 15px 0;
}
.content-nav img {
  height: 30px;
  width: 30px;
}
.content-title {
  display: flex;
}
.content-number {
  display: flex;
  flex-direction: column;
  margin-left: 15px;
  font-size: 12px;
  line-height: 15px;
}
.deal {
  color: #999999;
}
.content-price {
  color: #999999;
  font-size: 14px;
  line-height: 34px;
}
.pay-nav {
  width: 100%;
  display: flex;
  background-color: #FFFFFF;
  position: fixed;
  bottom: 0;
}
.pay-nav div{
  height: 49px;
}
.pay-nav .null {
  width: 63%;
  border-top:1px solid #92D4EF;
  border-left: none;
  border-right: none;
  box-sizing: border-box;
}
.pay-nav .go-pay {
  width: 100%;
  background-color:#92D4EF;
  color: #FFFFFF;
  text-align: center;
  line-height: 49px;
  font-size: 15px;
}
.link-fill {
  width: 37%;
}
.content-wrapper >>> .weui-cells:after{
  border:none;
}
</style>
